import { queryUserOrder, cancelOrder } from '../../services/order'
import { checkIfLogin } from '../../utils/check'
import { queryVehicleDetail } from '../../services/vehicle'
import { getPackageDetailInfo } from '../../services/inspect-project'
import Toast from '@vant/weapp/toast/toast'

const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    orderList:[],
    showDialogConfirm:false,
    dialogMsg:"",
    currentItem: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getOrderList()
  },

  onShow(){
    checkIfLogin()
    this.getOrderList()
  },

  async getOrderList(){
    let orderRes = await queryUserOrder({
      status: 1
    })
    if(orderRes.code === 200){
      this.setData({
        orderList: orderRes.rows
      })
    }
  },

  handleClick(event){
    console.log("event>>>", event)
    const orderId = event.detail
    wx.redirectTo({
      url: `/pages/appointment-detail/appointment-detail?orderId=${orderId}`,
    })
  },

  async handleEdit(event){
    let currentItem = event.detail
    const { id, appointDate, appointPackageId, appointPackageName, appointTime, plateNo, stationId, stationName, vehicleId  } = currentItem

    let vehicleRes = await queryVehicleDetail(vehicleId)
    console.log("vehicleRes>>>", vehicleRes)
    let vehicleType = ""
    if(vehicleRes.code === 200){
      vehicleType = vehicleRes.data.vehicleType
    }

    let detectProjectName = ""
    let packageInfoRes = await getPackageDetailInfo(appointPackageId)
    console.log("packageInfoRes>>>", packageInfoRes)
    if(packageInfoRes.code === 200){
      detectProjectName = packageInfoRes.data.detectProjectName
    }

    let glabalInfo = {
      id,
      appointDate,
      appointPackageId,
      appointPackageName,
      appointTime,
      detectProjectName,
      plateNo,
      stationId,
      stationName,
      vehicleId,
      vehicleType
    }
    app.globalData.globalInfo = glabalInfo
    wx.navigateTo({
      url: '/pages/inspection-project/inspection-project',
    })
  },

  handleCancel(event){
    let currentItem = event.detail
    this.setData({
      showDialogConfirm: true,
      dialogMsg: "是否确认取消预约?",
      currentItem,
    })
  },

  async handleConfirm(){
    let info = {
      id: this.data.currentItem.id
    }
    let cancelRes = await cancelOrder(info)
    if(cancelRes.code === 200){
      Toast.success('取消成功')
      this.getOrderList()
    }
  },

  handleDetail(event){
    console.log("查看详情>>>", event)
    let currentId = event.currentTarget.dataset.currentid
    wx.redirectTo({
      url: `/pages/appointment-detail/appointment-detail?orderId=${currentId}`,
    })
  }
})